package com.uniview.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.uniview.entity.po.ServiceOrders;
import com.uniview.entity.po.ServiceOrdersLogs;
import com.uniview.service.ServiceOrdersService;

public class OrdersTask {
	
	private Logger logger = Logger.getLogger(OrdersTask.class);
	
	@Autowired
	private ServiceOrdersService srviceOrdersService;

	private final static Integer STATUS = 5;

	public synchronized void updateOrderStatus() {
		try {
			logger.debug("=========开始执行关闭工单任务");
			Calendar ca = Calendar.getInstance();
//			ca.set(Calendar.DATE, -3);
			ca.add(Calendar.DATE, -3);
			Date date = ca.getTime();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateStr = dateFormat.format(date);
			ServiceOrdersLogs logs = null;
			logs = new ServiceOrdersLogs();
			logs.setCreateTime(new Date());
			logs.setCreator("系统管理员");
			logs.setHandler("关闭工单");
			logs.setReMark("客户超过三天未回复 系统自动关闭工单");
			logs.setStauts(STATUS);
			// 更新子订单的状态
			List<ServiceOrders> childList = srviceOrdersService.findChildOrdersByStauts(4, dateStr);
			if(childList != null && !childList.isEmpty()){
				for(ServiceOrders soChild:childList){
					logs.setOrderId(soChild.getId());
//					soChild.setModifyTime(new Date());
					soChild.setStatus("" + STATUS);
					srviceOrdersService.updateOrder(soChild, logs);
				}
			}
			
			// 更新没有未关闭的父订单的状态
			List<ServiceOrders> list = srviceOrdersService.findOrdersByStauts(4, dateStr);
			if (list != null && !list.isEmpty()) {
				for (ServiceOrders so : list) {
					List<ServiceOrders> child = srviceOrdersService.findOrdersByParentId(so.getId());
					if (child.isEmpty() && child.size() == 0) {
						logs.setOrderId(so.getId());
//						so.setModifyTime(new Date());
						so.setStatus("" + STATUS);
						srviceOrdersService.updateOrder(so, logs);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("=========结束执行关闭工单任务");
	}

}
